<?php
class Categories extends BlockInstance {
	public $CI;
	
	function Categories()
	{
		$this->CI =& get_instance();
	}
	
	function handle_proxy($bricabox_id, $params, $parent_name, $tpl_path, $instance, $parent)
	{
		switch($params['_action'])
		{
			case 'change_ctgy':
			{
				$content_id = $params['content_id'];
				$ctgy_id	= $params['value'];
				$this->CI->db->query('update contents set category_id = ? where id = ? and bricabox_id = ?', array($ctgy_id, $content_id, $bricabox_id));
				if ($ctgy_id > 0)
				{
					$cat = $this->CI->db->query('select name from categories where id = ?', $ctgy_id)->first_row()->name;
					echo "<a href=\"/entries/categorized/{$ctgy_id}\">{$cat}</a>";
				}
			}
			break;
			
			case 'rem_ctgy':
			{
				$ctgy_id = $params['value'];
				$this->CI->db->query('delete from categories where id = ?', array($ctgy_id));
			}
			break;
			
			case 'add_ctgy':
			{
				$name = $this->CI->input->post('value');
				if (strlen($name))
					$this->CI->db->query('insert into categories (name,bricabox_id) values(?,?)', array($name, $bricabox_id));
			}
			break;
		}
	}
	
	function __call($m, $a)
	{
		global $BBX;
		if (preg_match('/[a-z]+_([a-z]+)/', $m, $matches))
		{
			$this->CI->load->model('Membership_model');
			if ($matches[1] == 'content')
			{
				$this->CI->load->model('Bricabox_model');
				
				$content = $a[1];
				$data 	 = array(
					'block_instance' => $a[0],
					'bricabox'		 => $BBX['bricabox'],	// pass anyway so handle_proxy() can recreate the view via ajax
					'content'		 => $content,			// pass anyway so handle_proxy() can recreate the view via ajax
					'ctgys'			 => $this->CI->Bricabox_model->get_categories($BBX['bricabox']->id)
				);
				if ($content->category_id > 0)
					$data['cat'] = $this->CI->db->query('select * from categories where id = ?', array($content->category_id))->first_row();
				else
					$data['cat'] = false;
				$this->CI->load->view('blocks/categories/content', $data);
			}
			elseif ($matches[1] == 'homepage')
			{
				$this->CI->load->model('Membership_model');
				
				$data = array(
					'bricabox'		 => $BBX['bricabox'],	// pass anyway so handle_proxy() can recreate the view via ajax
					'block_instance' => $a[0],
					'cats'			 => $this->_load_all_cats()
				);
				$this->CI->load->view('blocks/categories/homepage', $data);
			}
		}
	}
	
	private function _load_all_cats()
	{
		global $BBX;
		
		$query = $this->CI->db->query('select * from categories where bricabox_id = ? order by name asc', array($BBX['bricabox']->id));
		if ($query->num_rows())
			return $query;
		else
			return false;
	}
}
?>